<script lang="tsx">
import { Input, RadioGroup, CheckboxGroup, RangePicker, Textarea, Select } from 'ant-design-vue'
import { $getAgentWxListForActivity,$apiGetMaterialImgList } from '@/api/activityManage/activityCreate/index'
import { h, ref, onMounted, inject, watch } from 'vue'
import { activityConfig, visibilityHandler } from '../activityConfig.js'
import GzMaterialModal from '@/components/link/UIComponents/GzMessageBox/GzMaterialModal.vue'
export default {
  props: {
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { attrs, emit, expose, slots }){
    // 表单实例
    const activityBasicInfoFormRef = ref()
    // 传递过来的图片信息
    const materialsInfo = ref({})
    onMounted(async () => {
    })

    // 接收父组件的创建活动的详细参数
    let activityDetailInfoInject: any = inject('activityDetailInfo')
    let activityDetailInfo: any = activityDetailInfoInject.value
    // 接收活动模板
    let activityTemplateDataRef : any = inject('activityTemplateData')
    let activityTemplateData : any = activityTemplateDataRef.value
    // 出资方列表： 出资方列表数据
    let payAuthListRef :any = inject('payAuthList')
    let payAuthList : any = payAuthListRef.value

    let GzMaterialModalRef:any = ref()

    // 表单规则（总） 默认所有字段必填 根据具体活动 某些字段可以不填 需要在组件挂载时合并传递过来的规则
    const formRules = ref({
      activityName: [ { required: true, message: '请输入活动名称', trigger: 'blur' } ],
      activityTime: [ { required: true, message: '请选择活动时间', trigger: 'change' } ],
      agentNo: [ { required: true, message: '请选择机构', trigger: ['blur','change'] } ],
      wxOfficalAppId: [ { required: true, message: '请选择微信公众号', trigger: ['blur','change'] } ],
      wxMiniProgramAppId: [ { required: true, message: '请选择微信小程序', trigger: ['blur','change'] } ],
      remark: [ { required: true, message: '请输入活动说明', trigger: 'blur' } ],
      activityImg: [ { required: true, tigger: ['blur','change'], message: '请上传活动图片' } ],
      imgUrl: [ { required: false } ],
      litePath: [{ required: true, message: '请选择游戏类型', trigger: ['blur','change'] }],
      // imgUrl: [ { required: true, tigger: ['blur','change'], validator: () => !vdata.saveObject.imgUrl ? Promise.reject('请上传公众号素材') : Promise.resolve() } ],
      // litePath2: [ { required: true, message: '请输入小程序页面副路由', trigger: 'blur' } ],
      activityImg2: [ { required: true, message: '请上传活动副页面主图', trigger: 'blur' } ],
      entryway: [ { required: true, message: '请选择流量入口', trigger: ['blur','change'] } ],
    })

    // 查询机构小程序/公众号列表接口  0微信公众号   1微信小程序 
    const officialList = ref([])
    const miniProgramList = ref([])
    async function getAgentWxList(agentNo){
      const [ res1, res2 ] = await Promise.all([$getAgentWxListForActivity({ agentNo, type: 0 }),$getAgentWxListForActivity({ agentNo, type: 1 })])
      officialList.value = res1.map(item => ({ label: item.name, value: item.appId }))
      miniProgramList.value = res2.map(item => ({ label: item.name, value: item.appId }))
    }


    // // 获取公众号素材列表
    // const officialMaterialsList = ref([])
    // async function getOfficialMaterialsList(){
    //   $apiGetMaterialImgList({activityTemplateNo:activityTemplateData.activityTemplateNo}).then(res=>{
    //     console.log(res,111111)
    //     officialMaterialsList.value = res
    //   })
    // }

    // getOfficialMaterialsList()

    // 监听机构变化 重新请求小程序/公众号列表
    watch(() => activityDetailInfo.agentNo, async (newVal,oldVal) => {
      if (newVal) {
        getAgentWxList(newVal)
      }
      if (newVal && oldVal) {  // 修改时重置微信小程序/公众号列表
        activityDetailInfo.wxOfficalAppId = null
        activityDetailInfo.wxMiniProgramAppId = null
      }
    }, { immediate: true })

    // field options handle
    function handleOptions(item) {
      if(item.name === 'wxOfficalAppId'){ // 微信公众号
        return officialList.value
      }
      if(item.name === 'wxMiniProgramAppId'){ // 微信小程序
        return miniProgramList.value
      }
      if(item.name === 'payAuthId'){  // 出资方列表
        return payAuthList.map(item => ({ label: item.ifName, value: item.payAuthId }))
      }
      return item.options
    }

    // 带tips的单组件渲染
    const FieldWithTip = (item: any) => {
      return (
        <a-form-item label={item.label} name={item.name}>
          { h(componentMap[item.tag], {
            ...item,
            disabled: props.isDetail,
            value: activityDetailInfo[item.name],
            onChange: (e) => onChangeHandle(e, item.name, item.tag)
          })}
          { item.tip && <span class="gz-tip-text">{ item.tip }</span> }
        </a-form-item>
      )
    }
    // 机构选择器 组件渲染
    const AgentSelect = (item: any) => {
      return (
        <a-form-item label={item.label} name={item.name}>
          <GzTreeSelect v-model:value={activityDetailInfo[item.name]} disabled={props.isDetail} />
        </a-form-item>
      )
    }
    // 图片上传
    const ImgUpload = (item: any) => {
      return (
        <a-form-item label={item.label} name={item.name}>
          <GzUpload v-model:src={activityDetailInfo[item.name]} disabled={props.isDetail} bizType={item.bizType} />
          { item.tip && <span class="gz-tip-text">{ item.tip }</span> }
        </a-form-item>
      )
    }
    // mediaUpload
    const mediaUpload =  (item:any) => {
      // return (
      //     <a-form-item label={item.label} name={item.name}>
      //               <div data-v-049b16ba="" style="padding: 20px 8px 8px;margin:8px 0 0;width:61px;height:66px;border:1px solid #d9d9d9;border-radius:4px;cursor: pointer;"><span role="img" aria-label="upload" class="anticon anticon-upload" onClick={openDialog} data-v-049b16ba=""><svg focusable="false" class="" data-icon="upload" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"></path></svg></span>上传</div>
      //               <div class="ant-upload-list-item ant-upload-list-item-undefined ant-upload-list-item-list-type-picture" data-v-049b16ba="" style="display: flex; align-items: center; gap: 8px;"><img src="https://jdyd-test.oss-cn-hangzhou.aliyuncs.com/henan/activity/9c09a5d5-db5e-4d1c-a6a9-16cb6ef1f406.png" alt="{{ file.name }}" data-v-049b16ba="" style="width: 48px; cursor: pointer;"><span data-v-049b16ba="" style="color: rgb(24, 144, 255); flex-grow: 1; cursor: pointer;">9c09a5d5-db5e-4d1c-a6a9-16cb6ef1f406.png</span><a href="javascript:;" data-v-049b16ba=""><span role="img" aria-label="delete" class="anticon anticon-delete" data-v-049b16ba="" style="color: rgba(0, 0, 0, 0.45);"><svg focusable="false" class="" data-icon="delete" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"></path></svg></span></a></div>

      //     </a-form-item>
        
      // )

      return (
        <a-form-item  label={item.label} name={item.name}>
        {!activityDetailInfo.imgUrl &&
          (<div  class="upload-area" style="padding: 20px 8px 8px;margin:8px 0 0;width:61px;height:66px;border:1px solid #d9d9d9;border-radius:4px;cursor: pointer;" onClick={openDialog}>
          <span role="img" aria-label="upload" class="anticon anticon-upload" onClick={openDialog} data-v-049b16ba=""><svg focusable="false" class="" data-icon="upload" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M400 317.7h73.9V656c0 4.4 3.6 8 8 8h60c4.4 0 8-3.6 8-8V317.7H624c6.7 0 10.4-7.7 6.3-12.9L518.3 163a8 8 0 00-12.6 0l-112 141.7c-4.1 5.3-.4 13 6.3 13zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"></path></svg></span>
          <span>上传</span>
        </div>)
        }
        {activityDetailInfo.imgUrl && (
        <div class="file-preview" style="width:304px;height:66px;margin:8px 0 0;padding:8px;border-radius:4px;border:1px solid #d9d9d9;display:flex;align-items:center;gap:8px;">
          <img 
          style="width:48px;height:27px;"
            src={activityDetailInfo.imgUrl} 
            alt='' 
            class="preview-image"
          />
          <div class="file-name" style="width:208px;height:44px;color:#1890FF;overflow:hidden;">{activityDetailInfo.imgUrl}</div>
          <a onClick={handleDelete} class="delete-btn">
            {/* <DeleteOutlined /> */}
            <svg style="color: rgba(0, 0, 0, 0.45);" focusable="false" class="" data-icon="delete" width="1em" height="1em" fill="currentColor" aria-hidden="true" viewBox="64 64 896 896"><path d="M360 184h-8c4.4 0 8-3.6 8-8v8h304v-8c0 4.4 3.6 8 8 8h-8v72h72v-80c0-35.3-28.7-64-64-64H352c-35.3 0-64 28.7-64 64v80h72v-72zm504 72H160c-17.7 0-32 14.3-32 32v32c0 4.4 3.6 8 8 8h60.4l24.7 523c1.6 34.1 29.8 61 63.9 61h454c34.2 0 62.3-26.8 63.9-61l24.7-523H888c4.4 0 8-3.6 8-8v-32c0-17.7-14.3-32-32-32zM731.3 840H292.7l-24.2-512h487l-24.2 512z"></path></svg>
          </a>
        </div>
      )}
      </a-form-item>
         
      )

      
    }
    // 组件映射表：将配置中的字符串映射到实际组件
    const componentMap = {
      // 基础组件
      'a-input': Input,  // 输入框
      'a-radio-group': RadioGroup,  // 单选框
      'a-checkbox-group': CheckboxGroup,  // 多选框
      'a-range-picker': RangePicker,  // 日期范围选择器
      'a-textarea': Textarea,  // 多行文本框
      'a-select': Select,  // 选择器

      // 
      'c-media-upload': mediaUpload,

      // 自定义组件 -- 具有通用性
      'c-field-with-tip': FieldWithTip, // 带tips的单组件渲染
      'c-agent-select': AgentSelect,  // 树形选择器
      'c-img-upload': ImgUpload,  // 图片上传
    }

    // 打开素材列表组件
    const openDialog = () =>{
      GzMaterialModalRef.value.show('',activityDetailInfo.wxOfficalAppId,activityTemplateData.activityTemplateNo)
    }

    const udateMaterials = (item) =>{
      activityDetailInfo.thumbMediaId = item.repMediaId
      activityDetailInfo.imgUrl = item.repUrl
    }

    const handleDelete = () =>{
      delete activityDetailInfo.thumbMediaId
      delete activityDetailInfo.imgUrl
    }

    /**
     * 修改表单项的值
     */
    const onChangeHandle = (e: any, name: string, tag: string) => {
      if(e === null || e === undefined){
        activityDetailInfo[name] = null
        // 特殊字段的关联清理
        if (name === 'activityTime') {  // 建议将字段名改为明确的时间范围字段
          activityDetailInfo.startTime = null
          activityDetailInfo.endTime = null
        }
        return
      }
      // 提取值的统一处理
      const value = e && typeof e === 'object' && 'target' in e
        ? e.target.value
        : e
      // 通用赋值
      activityDetailInfo[name] = value
      // 特殊字段的额外处理
      if (name === 'activityTime') {
        // 类型守卫确保是数组
        if (Array.isArray(value) && value.length === 2) {
          const [startTime, endTime] = value
          activityDetailInfo.startTime = startTime
          activityDetailInfo.endTime = endTime
        } else {
          // 处理非法数据或重置
          activityDetailInfo.startTime = null
          activityDetailInfo.endTime = null
        }
      }
    }

    // 表单校验事件
    async function validateFields(isDraft) {
      return new Promise((resolve, reject) => {
        activityBasicInfoFormRef.value.validateFields(isDraft ? ['activityName', 'litePath'] : undefined).then(() => {
          resolve()
        }).catch(err => {
          console.log('activityBasicInfo error', err)
          reject('请完善基础信息配置')
        })
      })
    }
    // 表单重置事件
    function clearValidate() {
      if (activityBasicInfoFormRef.value !== undefined) {
        activityBasicInfoFormRef.value.clearValidate()
      }
    }

    // 暴露表单校验事件
    expose({
      validateFields,
      clearValidate
    })

    return () => (
      <div>
        <a-form
          ref={activityBasicInfoFormRef}
          class="form"
          label-col={{ span: 4 }}
          wrapper-col={{ span: 8 }}
          model={activityDetailInfo}
          rules={formRules.value}
        >
        {activityConfig.activityBasicInfo.basefield.filter((item : any) => {
          // 过滤掉不在可用模板的字段
          return !item.usedTemplate?.length || item.usedTemplate.includes(activityTemplateData.activityTemplateNo)
        }).filter((item : any) => {
          return visibilityHandler(item.visibilityRules, activityDetailInfo)
        }).map((item : any, index: number) => { 
          if(!item.component){
            return (
              <a-form-item
                key={`${item.name}_${index}`}
                name={item.name}
                label={item.label}
              >
                { h(componentMap[item.tag], {
                  ...item,
                  options: handleOptions(item),
                  disabled: item.disabled || props.isDetail,
                  value: activityDetailInfo[item.name],
                  onChange: (e) => onChangeHandle(e, item.name, item.tag)
                })}
              </a-form-item>
            )
          }else {
            // 处理 自定义 类型的组件
            return typeof componentMap[item.component] === 'function' ? componentMap[item.component](item) : componentMap[item.component]
          }
        })}
        </a-form>
        <GzMaterialModal  ref={GzMaterialModalRef} onUdateMaterials={udateMaterials}/>
      </div>
    )
  }
}

</script>

<style lang="less" scoped>
.form{
  margin-left: 20px;
  margin-top: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number) {
  width: 100%;
}
</style>